<template>
<a-modal v-model:visible="state.visible" :width="720" title="Basic Modal" @ok="handleOk" @cancel="handleCancel">
    <div class="mb-10">
        <a-button type="primary" @click="addGoodsItem">添加商品</a-button>
    </div>
    <a-table :data-source="state.goodsList" :pagination="false">
        <a-table-column title="商品编码" key="goodsCode" :width="120" data-index="goodsCode">
            <template #default="{ record,index}">
                <a-input 
                v-model:value="record.goodsCode" 
                @keydown.enter="(event)=>getGoodsByCode(event,index)"
                @blur="(event)=>getGoodsByCode(event,index)"></a-input>  
            </template>     
        </a-table-column>
        <a-table-column title="商品名称" key="goodsCode" data-index="goodsName">
            <template #default="{ record }">
                {{ record.goodsName }} 
            </template>     
        </a-table-column>
        <a-table-column title="商品数量" key="quantity" :width="120" data-index="quantity">
            <template #default="{ record }">
                <a-input v-model:value="record.quantity"></a-input>  
            </template>     
        </a-table-column>
    </a-table>
</a-modal>
</template>
<script lang="ts" setup>
import { GoodsService } from "@/service";
import { GoodsTypes } from "@/type";
import { reactive,onMounted } from "vue";

const props = withDefaults(
    defineProps<{
    goodsList:GoodsTypes.GoodsType[]
}>(),{
    goodsList:()=>[]
}
)

const state = reactive<{
    visible: boolean;
    goodsList:GoodsTypes.GoodsType[]
}>({
    visible: true,
    goodsList:[]
});

const emit = defineEmits<{
    (e:"ok",values:GoodsTypes.GoodsType[]):void,
    (e:"cancel"):void
}>()

onMounted(()=>{
    state.goodsList = props.goodsList.map((goods)=>{
        return {
            ...goods,
            quantity:goods.quantity ?? 1
        }
    })
    console.log("state.goodsList->", state.goodsList)
})

const getGoodsByCode = async(event:Event,index:number)=>{
    let val = (event.target as HTMLInputElement).value;
    let res = await GoodsService.detailGoods(Number(val));
    if(res.code===0){
        state.goodsList[index].goodsCode = res.data.goodsCode;
        state.goodsList[index].goodsName = res.data.goodsName;
        state.goodsList[index].type = res.data.type;
        state.goodsList[index].salePrice = res.data.salePrice ;
        
    }
}

const addGoodsItem = ()=>{
    state.goodsList.push({quantity:1});
}

const handleOk = ()=>{
    emit("ok",state.goodsList);
}

const handleCancel = ()=>{
    emit("cancel");
}
</script>